package com.quanyan.user.web;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.user.model.vo.request.ReqFeedback;
import com.quanyan.user.model.vo.request.ReqQuestion;
import com.quanyan.user.model.vo.response.RespQuestion;
import com.quanyan.user.model.vo.response.RespQuestionCategory;
import com.quanyan.user.model.vo.response.RespQuestionDetail;
import com.quanyan.user.service.FeedbackService;
import com.quanyan.user.service.QuestionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 客服帮助模块接口
 * Created by huadongyang on 2016/11/7.
 */
@RestController
@RequestMapping(value = "/api/user/customerService")
public class CustomerServiceHelpController {
    private static final Logger logger = LoggerFactory.getLogger(CustomerServiceHelpController.class);

    @Autowired
    private QuestionService questionService;
    @Autowired
    private FeedbackService feedbackService;

    /**
     * 查询问题列表
     *
     * @param reqQuestion
     * @param result
     * @param request
     * @return
     */
    @RequestMapping(value = "/questionList", method = RequestMethod.POST, produces = "application/json")
    public APIResponse<PageObj<List<RespQuestion>>> getQuestionList(@RequestBody @Valid ReqQuestion reqQuestion, BindingResult result, HttpServletRequest request) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }

        if (reqQuestion == null || (reqQuestion != null && (reqQuestion.getPageNo() == null || reqQuestion.getPageSize() == null))) {
            return APIResponse.returnFail("请传入有效参数！");
        }

        APIResponse<PageObj<List<RespQuestion>>> apiResponse = null;
        try {

            apiResponse = questionService.queryQuestions(reqQuestion);
        } catch (Exception e) {
            logger.error("获取问题列表失败！：{}", e.getMessage());
            return APIResponse.returnFail("获取问题列表失败！");
        }
        return apiResponse;
    }

    /**
     * 获取问题分类列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/questionCategoryList", method = RequestMethod.POST, produces = "application/json")
    public APIResponse<List<RespQuestionCategory>> getQuestionCategoryList(HttpServletRequest request) {
        return questionService.queryQuestionCategories();
    }

    /**
     * 获取问题详情
     *
     * @param map
     * @param result
     * @return
     */
    @RequestMapping(value = "/getQuestionDetail", method = RequestMethod.POST, produces = "application/json")
    public APIResponse<RespQuestionDetail> getQuestionDetail(@RequestBody Map<String, Integer> map, BindingResult result) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }

        Integer id = map.get("id");
        if (id == null) {
            return APIResponse.returnFail("请求参数不正确!");
        }

        return questionService.getQuestionDetail(id);
    }

    /**
     * 保存意见反馈
     *
     * @param reqFeedback
     * @param result
     * @return
     */
    @RequestMapping(value = "/saveFeedback", method = RequestMethod.POST, produces = "application/json")
    public APIResponse saveFeedback(@RequestBody ReqFeedback reqFeedback, BindingResult result) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        try {
            feedbackService.saveFeedback(reqFeedback);
        } catch (Exception e) {
            logger.error("保存用户意见反馈失败!:{}", e.getMessage());
            return APIResponse.returnFail("保存用户意见反馈失败!");
        }

        return APIResponse.returnSuccess();
    }

    @RequestMapping(value = "/statsSolveQuestionNum", method = RequestMethod.POST, produces = "application/json")
    public APIResponse statsSolveQuestionNum(@RequestBody Map map, BindingResult result,HttpServletRequest request) {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        Integer id = (Integer)map.get("id");
        Integer solve = (Integer) map.get("solve");
        Integer isCancel = (Integer) map.get("isCancel");
        Integer uid = (Integer)map.get("uid");
        if (id == null || id <=0  || solve == null || isCancel == null) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        String ip = getIp(request);

        return questionService.statsSolveQuestionNum(id, solve.byteValue(),isCancel.byteValue(), uid, ip);
    }

    @RequestMapping(value = "/statsQuestionPVandUV", method = RequestMethod.POST, produces = "application/json")
    public APIResponse statsQuestionPVandUV(@RequestBody Map map, BindingResult result, HttpServletRequest request){
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }

        Integer id = (Integer) map.get("id");
        Integer uid = (Integer) map.get("uid");
        if (id == null || id <=0 ) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }

        String ip = getIp(request);

        logger.info("访问接口ip：{}", ip);
        return questionService.statsQuestionPVandUV(id,uid,ip);
    }

    private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (StringUtil.isBlankOrNull(ip) || "unknown".equalsIgnoreCase(ip)) {
            String ips = request.getHeader("X-Forwarded-For");
            if (StringUtil.isBlankOrNull(ips) || "unknown".equalsIgnoreCase(ips)){
                ip = request.getRemoteAddr();
            }else {
                ip = ips.split(",")[0];
            }
        }
        return ip;
    }
}
